<?php
/**
 * Created by PhpStorm.
 * User: jwb
 * Date: 2020/5/9
 * Time: 12:29
 */

namespace App\Services;


use App\Models\Conversion;
use App\Patent;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class StatisticsService
{
    public function patentData($states)
    {
        $count = [];
        $start_date = request()->start_date?Carbon::parse(request()->start_date)->toDateString():null;
        $end_date = request()->end_date?Carbon::parse(request()->end_date)->toDateString():Carbon::now()->toDateString();
        $states[0] = '其他';
        foreach($states as $state_id=>$state){
            $count[$state_id] = $this->getPatentGroupByType($state_id,$start_date,$end_date);
        }
        return $count;
    }

    public function getPatentGroupByType($patent_state,$start_date=null,$end_date=null)
    {
        $where = [['patent_state',$patent_state]];
        if($start_date){
            $where[] = ['apply_date','>=',$start_date];
        }
        if($end_date){
            $where[] = ['apply_date','<=',$end_date];
        }
        return Patent::select(DB::raw('count(*) as count,patent_type_id'))
            ->where($where)
            ->groupBy('patent_type_id')
            ->pluck('count','patent_type_id');
    }
    public function getStartDate($start_date)
    {
        if(!$start_date){
            return null;
        }
        return Carbon::parse($start_date)->toDateString();

    }
    public function getEndDate($end_date)
    {
        if(!$end_date){
            return null;
        }
        return Carbon::parse($end_date)->toDateString();
    }
    public function conversionData()
    {
        $where = [];
        $start_date = $this->getStartDate(request()->start_date);
        $end_date = $this->getEndDate(request()->end_date);
        if($start_date){
            $where[] = ['apply_date','>=',$start_date];
        }
        if($end_date){
            $where[] = ['apply_date','<=',$end_date];
        }
        return Conversion::select(DB::raw('count(*) as count,type_id'))
            ->where($where)
            ->groupBy('type_id')
            ->pluck('count','type_id');
    }
}